<template>
    <div>

        <el-form :model="formData" ref="form" :rules="rules" label-width="80px" :inline="true" size="normal"
            class="demo-fore-inline">
            <div>
    
                <el-form-item label="单据日期" prop="date">
                    <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
                </el-form-item>
                <el-form-item label="单据编号"  prop="number">
                    <el-input v-model="formData.number"></el-input>
                </el-form-item> 
                
            </div>
            <div>
                <el-form-item>
                    <el-button plain @click="insertTr" type="primary">插入行</el-button>
                 
                    <el-button plain>扫码录入</el-button>
                </el-form-item>
            </div>
            <div class="ant-col" style="margin-right: 10px;">
        
        </div>
        </el-form>
        <el-table :data="tableData" ref="tableRef" show-summary style="width: 100%">
          <el-table-column label="仓库" width="120">
          <template #default="{ row }">
            <el-select v-model="row.dname" clearable style="width: 280px; margin-left: 10px;" placeholder="请选择仓库"
              @change="onChangeDepotSelect(row.dname)">
              <el-option v-for="depot in depots" :key="depot.id" :label="depot.name" :value="depot.id" />
            </el-select>
          </template>
        </el-table-column>
            
        <el-table-column width="120">
          <template #default="{ row }">

            <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
             v-perm:depot:other_in:insert:info="info">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>

            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="条码" width="120">
          <template #default="{ row }">
            <el-input v-model="row.barCode"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="名称" width="120">
          <template #default="{ row }">
            <el-input v-model="row.materialName"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="120">
          <template #default="{ row }">
            <el-input v-model="row.standard"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="120">
          <template #default="{ row }">
            <el-input v-model="row.totalOperNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="调入仓库" width="120">
          <template #default="{ row }">
          <el-select v-model="row.anotherDepotId" placeholder="" clearable filterable>
            <el-option v-for="item in depotname"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
    
          </template>
        </el-table-column>
        <el-table-column label="单位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.commodityUnit"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template #default="{ row }">
            <el-input v-model="row.operNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120">
          <template #default="{ row }">
            <el-input v-model="row.wholesaledecimal"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="{ row }">
            <el-input v-model="row.allPrice"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="100">
          <template #default="{ row }">
            <el-input v-model="row.totalOut"></el-input>
          </template>
        </el-table-column>
      </el-table>
        <el-form-item style="">
            <el-button plain @click="onSubmit" type="primary">确定</el-button>
                <el-button>重置</el-button>
        </el-form-item>
    </div>

<el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="70%"
    style="margin-left: 350px;margin-top: 200px">
    <router-view @close="closeDialog" @saveSaleinorder="saveSaleinorder" :data="data" :currentDepotId="currentDepotId"></router-view>
  </el-dialog>
  </template>
<script setup>
// 导入Vue中的ref和defineEmits函数
import { ref, defineEmits,onMounted, defineProps } from 'vue'

// 使用ref函数创建一个响应式的数据
// 使用defineEmits函数定义可以触发的自定义事件
import request from '@/api/request'
import router from '@/router';
import reqeust from '@/api/request'
import { ElMessage } from "element-plus";

let props = defineProps(["data"]);
let emits = defineEmits(['close'])
let formData = ref({ ...props.data })

let ruleForm = ref({})
const tableData = ref([
  { barCode: '', categoryName: '', color: '', commodityUnit: '', materialName: '', mfrs: '', model: '', sku: '', 
  standard: '', totalIn: '', totalOperNumber: '', totalOut: '', wholesaledecimal: '', basicnumber: '', allprice: '' }
]);

const visible = ref(false);
const title = ref("");
const data = ref({});

const insertTr = () => {
  tableData.value.push({
    barCode: '',
    categoryName: '',
    color: '',
    commodityUnit: '',
    materialName: '',
    mfrs: '',
    model: '',
    sku: '',
    standard: '',
    totalIn: '',
    totalOperNumber: '',
    totalOut: '',
    wholesaledecimal: '',
    basicnumber: '',
    allPrice: '',
    mid: '',
    aid: '',
    id: '',
    operNumber: 1, // 默认数量
    taxRate: '',
    taxMoney: '',
    taxLastMoney: '',
    dname: '',
    depotId: '' // 新行的仓库默认空值
  });
};
console.log(formData.value.id);

const loadData = () => {
  request({
    url: '/erpmaterialinventory/find',
    method: 'get',
    params: {
      headerId: formData.value.id
    }
  }).then(res => {
    tableData.value = res.data
    console.log(res.data);
    
  }).catch(err => {
    console.error(err);
  });
};
loadData();

// submitTable();
let submitTable = ()=>{
    console.log(tableData.value)
}
onMounted(() => {
  // 从本地存储获取当前的订单编号，如果不存在则默认为1
  let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);

  // 自增
  currentOrderNumber++;

  // 格式化为10位数
  const formattedOrderNumber = currentOrderNumber.toString().padStart(10, '0');

  // 将生成的订单编号赋值到表单
  ruleForm.value.number = formattedOrderNumber;

  // 将新的订单编号存储到本地存储中，便于下次使用
  localStorage.setItem('orderNumber', currentOrderNumber.toString());

  // depotId.value = props.data.erpDepot.id
});


// let depotId = ref(null)
// let anotherDepotId = ref(null)

let onSubmit = () => {

    const data = {
        erpDepotHead: {
            id: formData.value.id,
            number: ruleForm.value.number,
            organId: ruleForm.organId,
            creator: '1',
            changeAmount: '0',
            totalPrice: tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0), // 计算合计金额
            status: '0'
        },
        erpDepotItems: tableData.value.map(row => ({
            headerId:  formData.value.id,
            materialId: row.mid,
            materialExtendId: row.aid,
            materialUnit: row.commodityUnit,
            sku: row.sku,
            operNumber: row.operNumber,
            unitPrice: row.wholesaledecimal,
            allPrice: row.allPrice,
            remark: row.remark || '',
            taxRate: row.taxRate,
            taxMoney: row.taxMoney,
            depotId: row.depotId,
            anotherDepotId: row.anotherDepotId
        }))
    };
    console.log(data);
    
    request.post('sale/insertdepotdb', {
      ...data
    }).then(resp => {
      close();
      console.log(resp)
    })


    
}

let close=()=>{
    emits('close')
}

let closeDialog =()=>{
    visible.value = false
}

let supname = ref([])
reqeust.get('/depot/findSupplier'+'/'+0,{method:'get'}).then(resp => {
    console.log(resp);
    
    supname.value = resp.data
})

let depotname = ref([])
request.get('/depot/findDepot').then(resp=>{
    depotname.value = resp.data
    console.log(resp.data);
    
})
 let randomID = ""
 let generateRandomID=()=>{
    const characters ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
     const idLength = 16; // 字符串长度这里生成16位的 
    
        for (let i = 0; i< idLength; i++){
        const randomIndex = Math.floor(Math.random()* characters.length); 
        randomID += characters.charAt(randomIndex);
    }
console.log(randomID)
return randomID;
}
generateRandomID();

const info = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
};

const onChangeDepotSelect = (depotId) => {
    currentDepotId.value = depotId; // 更新当前选择的仓库 ID
};

const currentDepotId = ref('');
// 接收并显示保存的数据a
const saveSaleinorder = (selectedItems) => {
  selectedItems.forEach(item => {
    const emptyRowIndex = tableData.value.findIndex(row => !row.barCode); // 查找第一个空行
    if (emptyRowIndex !== -1) {
      // 将选中的商品填入空行
      const row = tableData.value[emptyRowIndex];
      Object.assign(row, {
        barCode: item.barCode,
        categoryName: item.categoryName,
        color: item.color,
        commodityUnit: item.commodityUnit,
        materialName: item.materialName,
        mfrs: item.mfrs,
        model: item.model,
        sku: item.sku,
        standard: item.standard,
        totalIn: item.totalIn,
        totalOperNumber: item.totalOperNumber,
        totalOut: item.totalOut,
        wholesaledecimal: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allPrice: item.allPrice,
        mid: item.mid,
        aid: item.aid,
        operNumber: 1, // 默认数量
        taxRate: item.taxRate,
        taxMoney: item.taxMoney,
        taxLastMoney: item.taxLastMoney,
        dname: currentDepotId.value, // 使用当前选择的仓库
      });
    } else {
      // 添加新行
      tableData.value.push({
        barCode: item.barCode,
        categoryName: item.categoryName,
        color: item.color,
        commodityUnit: item.commodityUnit,
        materialName: item.materialName,
        mfrs: item.mfrs,
        model: item.model,
        sku: item.sku,
        standard: item.standard,
        totalIn: item.totalIn,
        totalOperNumber: item.totalOperNumber,
        totalOut: item.totalOut,
        wholesaledecimal: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allPrice: item.allPrice,
        mid: item.mid,
        aid: item.aid,
        operNumber: 1, // 默认数量
        taxRate: item.taxRate,
        taxMoney: item.taxMoney,
        taxLastMoney: item.taxLastMoney,
        dname: currentDepotId.value, // 使用当前选择的仓库
      });
    }
  });
  console.log("已添加商品:", selectedItems);
};

</script>

<style scoped>
.demo-fore-inline .el-input {
    --el-input-width: 200px;
}
</style>
